package com.freeter.modules.gjs.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.freeter.modules.gjs.entity.TransferRequest;
import com.freeter.modules.gjs.mapper.TransferRequestMapper;
import com.freeter.modules.gjs.service.TransferRequestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.freeter.modules.gjs.entity.TransferItems;
import com.freeter.modules.gjs.mapper.TransferItemsMapper;
import com.freeter.modules.gjs.entity.AppRequestRecord;
import com.freeter.modules.gjs.mapper.AppRequestRecordMapper;
import com.freeter.modules.gjs.entity.StockStatus;
import com.freeter.modules.gjs.mapper.StockStatusMapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Value;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;

@Service
public class TransferRequestServiceImpl implements TransferRequestService {
    @Autowired
    private TransferRequestMapper transferRequestMapper;
    @Autowired private TransferItemsMapper transferItemsMapper;
    @Autowired private AppRequestRecordMapper appRequestRecordMapper;
    @Autowired private StockStatusMapper stockStatusMapper;
    @Value("${calc.ticket.folder:/tmp/calc_ticket}")
    private String calcTicketFolder;

    @Override
    public List<TransferRequest> getAllTransferRequests() {
        Wrapper<TransferRequest> wrapper = new EntityWrapper<>();
        wrapper.eq("is_deleted", 0);
        return transferRequestMapper.selectList(wrapper);
    }

    @Override
    public TransferRequest getTransferRequestById(Long id) {
        return transferRequestMapper.selectById(id);
    }

    @Override
    public TransferRequest getTransferRequestByRequestNo(String requestNo) {
        Wrapper<TransferRequest> wrapper = new EntityWrapper<>();
        wrapper.eq("request_no", requestNo).eq("is_deleted", 0);
        List<TransferRequest> list = transferRequestMapper.selectList(wrapper);
        return list.isEmpty() ? null : list.get(0);
    }

    @Override
    public List<TransferRequest> getTransferRequestsByUserId(Long userId) {
        Wrapper<TransferRequest> wrapper = new EntityWrapper<>();
        wrapper.eq("user_id", userId).eq("is_deleted", 0);
        return transferRequestMapper.selectList(wrapper);
    }

    @Override
    public List<TransferRequest> getTransferRequestsByFromSiteCode(String fromSiteCode) {
        Wrapper<TransferRequest> wrapper = new EntityWrapper<>();
        wrapper.eq("from_site_code", fromSiteCode).eq("is_deleted", 0);
        return transferRequestMapper.selectList(wrapper);
    }

    @Override
    public List<TransferRequest> getTransferRequestsByToSiteCode(String toSiteCode) {
        Wrapper<TransferRequest> wrapper = new EntityWrapper<>();
        wrapper.eq("to_site_code", toSiteCode).eq("is_deleted", 0);
        return transferRequestMapper.selectList(wrapper);
    }

    @Override
    public List<TransferRequest> getTransferRequestsByStatus(String status) {
        Wrapper<TransferRequest> wrapper = new EntityWrapper<>();
        wrapper.eq("status", status).eq("is_deleted", 0);
        return transferRequestMapper.selectList(wrapper);
    }

    @Override
    public List<TransferRequest> getTransferRequestsByApprovedBy(String approvedBy) {
        Wrapper<TransferRequest> wrapper = new EntityWrapper<>();
        wrapper.eq("approved_by", approvedBy).eq("is_deleted", 0);
        return transferRequestMapper.selectList(wrapper);
    }

    @Override
    public TransferRequest createTransferRequest(TransferRequest transferRequest) {
        transferRequestMapper.insert(transferRequest);
        return transferRequest;
    }

    @Override
    public TransferRequest updateTransferRequest(Long id, TransferRequest transferRequest) {
        transferRequest.setId(id);
        transferRequestMapper.updateById(transferRequest);
        return transferRequest;
    }

    @Override
    public boolean deleteTransferRequest(Long id) {
        return transferRequestMapper.deleteById(id) > 0;
    }

    @Override
    public boolean deleteTransferRequestByRequestNo(String requestNo) {
        Wrapper<TransferRequest> wrapper = new EntityWrapper<>();
        wrapper.eq("request_no", requestNo);
        return transferRequestMapper.delete(wrapper) > 0;
    }

    @Override
    public List<TransferRequest> getTransferRequestsByCondition(String name, Integer state) {
        Wrapper<TransferRequest> wrapper = new EntityWrapper<>();
        if (name != null) wrapper.eq("name", name);
        if (state != null) wrapper.eq("state", state);
        wrapper.eq("is_deleted", 0);
        return transferRequestMapper.selectList(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean relocRequest(Map<String, Object> req) throws Exception {
        // 1. 参数提取
        String fromSite = (String) req.get("from_site");
        String toSite = (String) req.get("to_site");
        List<Map<String, Object>> itemList = (List<Map<String, Object>>) req.get("item_list");
        String remarks = (String) req.get("remarks");
        String requestId = (String) req.get("request_id");
        Long userId = req.get("user_id") == null ? null : Long.valueOf(req.get("user_id").toString());
        String csrfToken = (String) req.get("csrf_token");
        // 2. 幂等校验
        if (requestId != null && userId != null && csrfToken != null) {
            AppRequestRecord exist = appRequestRecordMapper.selectOne(new AppRequestRecord() {{
                setUserId(userId); setCsrfToken(csrfToken); setRequestId(requestId); setActionType("reloc-request");
            }});
            if (exist != null) return true;
        }
        // 3. 参数校验
        if (fromSite == null || toSite == null || itemList == null || itemList.isEmpty()) {
            throw new Exception("Missing required field");
        }
        // 4. 写入transfer_request
        TransferRequest tr = new TransferRequest();
        tr.setFromSiteCode(fromSite);
        tr.setToSiteCode(toSite);
        tr.setUserId(userId);
        tr.setRemarks(remarks);
        tr.setStatus("Pending");
        tr.setCreatedAt(java.time.LocalDateTime.now());
        transferRequestMapper.insert(tr);
        // 5. 写入transfer_items
        for (Map<String, Object> item : itemList) {
            String itemCode = (String) item.get("item_code");
            Double qty = item.get("qty") == null ? null : Double.valueOf(item.get("qty").toString());
            if (itemCode == null || qty == null) continue;
            TransferItems ti = new TransferItems();
            ti.setTransferNo(tr.getRequestNo());
            ti.setItemCode(itemCode);
            ti.setQuantity(new java.math.BigDecimal(qty));
            ti.setFromSiteCode(fromSite);
            ti.setToSiteCode(toSite);
            ti.setStatus("Pending");
            ti.setCreatedAt(java.time.LocalDateTime.now());
            transferItemsMapper.insert(ti);
            // 6. 更新库存（如有需要）
            // StockStatus stock = stockStatusMapper.selectById(...);
            // stock.setHoldQty(...);
            // stockStatusMapper.updateById(stock);
        }
        // 7. 写入app_request_record
        if (requestId != null && userId != null && csrfToken != null) {
            AppRequestRecord record = new AppRequestRecord();
            record.setUserId(userId);
            record.setCsrfToken(csrfToken);
            record.setRequestId(requestId);
            record.setActionType("reloc-request");
            record.setRecordTime(new java.util.Date());
            appRequestRecordMapper.insert(record);
        }
        // 8. 可选：写本地调拨文件
        // ...
        return true;
    }

    @Override
    public int getRelocPendingCount(Map<String, Object> params) {
        // 只统计当前用户有权限的、状态为Pending的调拨申请
        Wrapper<TransferRequest> wrapper = new EntityWrapper<>();
        wrapper.eq("status", "Pending");
        // 可根据params补充项目/站点等过滤条件
        return transferRequestMapper.selectCount(wrapper);
    }

    @Override
    public List<Map<String, Object>> getRelocPendingList(Map<String, Object> params) {
        // 查询所有状态为Pending的调拨申请，支持分页/过滤
        Wrapper<TransferRequest> wrapper = new EntityWrapper<>();
        wrapper.eq("status", "Pending");
        // 可根据params补充项目/站点等过滤条件
        List<TransferRequest> list = transferRequestMapper.selectList(wrapper);
        List<Map<String, Object>> result = new ArrayList<>();
        for (TransferRequest tr : list) {
            Map<String, Object> map = new java.util.HashMap<>();
            map.put("request_no", tr.getRequestNo());
            map.put("from_site_code", tr.getFromSiteCode());
            map.put("to_site_code", tr.getToSiteCode());
            map.put("status", tr.getStatus());
            map.put("created_at", tr.getCreatedAt());
            map.put("remarks", tr.getRemarks());
            result.add(map);
        }
        return result;
    }

    @Override
    public void cancelRelocPending(Map<String, Object> req) {
        // 1. 参数提取
        String requestNo = (String) req.get("request_no");
        if (requestNo == null) throw new RuntimeException("request_no is required");
        // 2. 查询并校验状态
        Wrapper<TransferRequest> wrapper = new EntityWrapper<>();
        wrapper.eq("request_no", requestNo).eq("status", "Pending");
        // TransferRequest tr = transferRequestMapper.selectOne(wrapper);
        List<TransferRequest> trList = transferRequestMapper.selectList(wrapper);
        TransferRequest tr = (trList != null && trList.size() > 0) ? trList.get(0) : null;
        if (tr == null) throw new RuntimeException("Pending request not found");
        // 3. 更新状态为Cancelled
        tr.setStatus("Cancelled");
        transferRequestMapper.updateById(tr);
    }

    @Override
    public void approveRelocRequest(Map<String, Object> req) {
        // 1. 参数提取
        String requestNo = (String) req.get("request_no");
        if (requestNo == null) throw new RuntimeException("request_no is required");
        // 2. 查询并校验状态
        Wrapper<TransferRequest> wrapper = new EntityWrapper<>();
        wrapper.eq("request_no", requestNo).eq("status", "Pending");
        // TransferRequest tr = transferRequestMapper.selectOne(wrapper);
        List<TransferRequest> trList = transferRequestMapper.selectList(wrapper);
        TransferRequest tr = (trList != null && trList.size() > 0) ? trList.get(0) : null;
        if (tr == null) throw new RuntimeException("Pending request not found");
        // 3. 更新状态为Approved
        tr.setStatus("Approved");
        transferRequestMapper.updateById(tr);
    }

    @Override
    public int getRelocNonRecCount(Map<String, Object> params) {
        // 统计当前用户有权限的、状态为Approved但未接收的调拨申请
        Wrapper<TransferRequest> wrapper = new EntityWrapper<>();
        wrapper.eq("status", "Approved");
        // 可根据params补充项目/站点等过滤条件
        return transferRequestMapper.selectCount(wrapper);
    }

    @Override
    public List<Map<String, Object>> getRelocNonRecList(Map<String, Object> params) {
        // 查询所有状态为Approved但未接收的调拨申请，支持分页/过滤
        Wrapper<TransferRequest> wrapper = new EntityWrapper<>();
        wrapper.eq("status", "Approved");
        // 可根据params补充项目/站点等过滤条件
        List<TransferRequest> list = transferRequestMapper.selectList(wrapper);
        List<Map<String, Object>> result = new ArrayList<>();
        for (TransferRequest tr : list) {
            Map<String, Object> map = new java.util.HashMap<>();
            map.put("request_no", tr.getRequestNo());
            map.put("from_site_code", tr.getFromSiteCode());
            map.put("to_site_code", tr.getToSiteCode());
            map.put("status", tr.getStatus());
            map.put("created_at", tr.getCreatedAt());
            map.put("remarks", tr.getRemarks());
            result.add(map);
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void relocReceive(Map<String, Object> req) {
        // 1. 参数提取
        String requestNo = (String) req.get("request_no");
        List<String> photos = (List<String>) req.get("photos");
        List<String> videos = (List<String>) req.get("videos");
        String signature = (String) req.get("signature");
        Double latitude = req.get("latitude") == null ? null : Double.valueOf(req.get("latitude").toString());
        Double longitude = req.get("longitude") == null ? null : Double.valueOf(req.get("longitude").toString());
        String requestId = (String) req.get("request_id");
        Long userId = req.get("user_id") == null ? null : Long.valueOf(req.get("user_id").toString());
        String csrfToken = (String) req.get("csrf_token");
        // 2. 幂等校验
        if (requestId != null && userId != null && csrfToken != null) {
            AppRequestRecord exist = appRequestRecordMapper.selectOne(new AppRequestRecord() {{
                setUserId(userId); setCsrfToken(csrfToken); setRequestId(requestId); setActionType("reloc-receive");
            }});
            if (exist != null) return;
        }
        // 3. 查询调拨单
        Wrapper<TransferRequest> wrapper = new EntityWrapper<>();
        wrapper.eq("request_no", requestNo).eq("status", "Approved");
        // TransferRequest tr = transferRequestMapper.selectOne(wrapper);
        List<TransferRequest> trList = transferRequestMapper.selectList(wrapper);
        TransferRequest tr = (trList != null && trList.size() > 0) ? trList.get(0) : null;
        if (tr == null) throw new RuntimeException("Approved request not found");
        // 4. 更新调拨单状态为Completed
        tr.setStatus("Completed");
        transferRequestMapper.updateById(tr);
        // 5. 记录app_request_record
        if (requestId != null && userId != null && csrfToken != null) {
            AppRequestRecord record = new AppRequestRecord();
            record.setUserId(userId);
            record.setCsrfToken(csrfToken);
            record.setRequestId(requestId);
            record.setActionType("reloc-receive");
            record.setRecordTime(new java.util.Date());
            appRequestRecordMapper.insert(record);
        }
        // 6. TODO: 处理图片/签名保存、经纬度、事务明细、库存调整等（如需100%还原Node.js细节可继续补全）
    }
} 